package com.zsc.edu.testlistview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

class ListViewAdapter extends ArrayAdapter<MyItem> {
     int item_layout_id;

    public ListViewAdapter(@NonNull  Context context, int resource, @NonNull  List<MyItem> objects) {
        super(context, resource, objects);
        item_layout_id = resource;
    }

    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        View view;
        MyItemViewHolder myItemViewHolder;
        if (convertView == null){ // 如果 convertView 不存在
            // 单项的布局的资源id, 将其 inflate 出来
            view = LayoutInflater.from(getContext()).inflate(this.item_layout_id, parent, false);

            myItemViewHolder = new MyItemViewHolder();
            // 从单项的布局中，根据 id 获得 UI 控件的实例
            myItemViewHolder.item_image_view = view.findViewById(R.id.item_image_view);
            myItemViewHolder.item_text_view = view.findViewById(R.id.item_text_view);

            // 把 myItemViewHolder 保存到 tag
            view.setTag(myItemViewHolder);
        }else{ //  convertView 已经存在
            view = convertView;
            // 从 tag 中 取出 之前保存的 myItemViewHolder
            myItemViewHolder = (MyItemViewHolder)view.getTag();
        }

        // 根据当前位置 position，获得数据 MyItem
        MyItem myItem = this.getItem(position);

        // TextView 设置字符串资源
        myItemViewHolder.item_text_view.setText(myItem.getString_id());
        // ImageView 设置图片资源
        myItemViewHolder.item_image_view.setImageResource(myItem.getImage_id());

        // 返回准备完毕的view
        return view;
    }
}
